package link.anyauto.dtbinding.util;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.google.gson.Gson;

import java.lang.reflect.Type;

import link.anyauto.dtbinding.base.App;

/**
 * Created by LYQ on 2016/7/26.
 */
public class StorageUtil {

    static SharedPreferences getSp(){
        return PreferenceManager.getDefaultSharedPreferences(App.getApp());
    }

    static SharedPreferences.Editor getEditor() {
        return getSp().edit();
    }

    public static String getStr(String key) {
        return getStr(key, null);
    }

    public static String getStr(String key, String _default) {
        return getSp().getString(key, _default);
    }

    public static <T> T get(String key, Class<T> clz) {
        String src = getStr(key, null);
        if(TextUtils.isEmpty(src)) {
            return null;
        } else {
            return GsonUtil.gson.fromJson(src, clz);
        }
    }

    public static <T> T get(String key, Type type) {
        String src = getStr(key, null);
        if(TextUtils.isEmpty(src)) {
            return null;
        } else {
            return GsonUtil.gson.fromJson(src, type);
        }
    }

    public static void save(String key, String value) {
        if(value != null) {
            getEditor().putString(key, value).commit();
        } else {
            getEditor().remove(key).commit();
        }
    }

    public static void save(String key, Object value) {
        if(value != null) {
            save(key, GsonUtil.gson.toJson(value));
        } else {
            save(key, (String) null);
        }
    }

}
